<?php

namespace app\model\customer;

use app\model\BaseModel;
use app\model\device\DeviceBaseModel;
use app\service\system\AreaService;
use think\db\BaseQuery;
use think\db\exception\DbException;
use think\model\concern\SoftDelete;
use think\model\relation\BelongsTo;
use think\model\relation\HasMany;

/**
 * 职场模型
 * @property mixed $province_id
 * @property mixed $city_id
 * @property mixed $district_id
 * @property mixed $uuid
 */
class WorkPlaceModel extends BaseModel
{
    use SoftDelete;

    protected $table = 'work_place';

    /**
     * 对于关联模型: 使用append不需要再使用with预加载
     * 对于获取器: 使用append, 直接会在返回的数组里
     * @var string[]
     */
    protected $append = [
        'province',
        'city',
        'district',
        'device_num',
    ];

    /**
     * 基于用户的职场
     * @param BaseQuery $query
     * @param numeric $customer_base_id 0 为全部
     * @return void
     */
    public function scopeCustomer(BaseQuery $query, $customer_base_id = 0)
    {
        if ($customer_base_id > 0) {
            $query->where('customer_base_id', $customer_base_id);
        }
    }


    public function getProvinceAttr()
    {
        $service = new AreaService();
        return $service->getNameById($this->province_id);
    }

    public function getCityAttr()
    {
        $service = new AreaService();
        return $service->getNameById($this->city_id);
    }

    public function getDistrictAttr()
    {
        $service = new AreaService();
        return $service->getNameById($this->district_id);
    }

    /**
     * 设备数量
     * @return int
     * @throws DbException
     */
    public function getDeviceNumAttr(): int
    {
        $modelDevice = new DeviceBaseModel();
        $count = $modelDevice->where('work_place_uuid', $this->uuid)->count('*');
        return (int)$count;
    }

    /**
     * 职场的设备列表, 一对多
     * @return HasMany
     */
    public function device(): HasMany
    {
        return $this->hasMany(DeviceBaseModel::class, 'work_place_uuid', 'uuid');
    }

    /**
     * @return BelongsTo
     */
    public function customer(): BelongsTo
    {
        return $this->belongsTo(CustomerBaseModel::class, 'customer_base_id', 'id');
    }


}